package com.study.util;

import java.util.ArrayList;
import java.util.List;

import com.study.model.AuthConfig;
import com.study.model.Dynatree;

public class AdaptationTree {

	public static List<Dynatree> getResultTrees(List<AuthConfig> authconfigEntities) throws Exception {
		List<Dynatree> resultTrees = new ArrayList<Dynatree>();
		Dynatree rootTree = getRootTree(authconfigEntities);
		getTreeChildren(rootTree, authconfigEntities);
		resultTrees.add(rootTree);
		return resultTrees;

	}

	public static Dynatree getRootTree(List<AuthConfig> authconfigEntities) throws Exception {
		Dynatree rootTree = new Dynatree();
		List<AuthConfig> authconfigEntities2 = new ArrayList<AuthConfig>();
		for (AuthConfig authconfigEntity : authconfigEntities) {
			if (authconfigEntity.getPid() == 0) {
				authconfigEntities2.add(authconfigEntity);
			}
		}
		if (authconfigEntities2.size() == 0) {
			return rootTree;
		}
		AuthConfig authconfigEntityRoot = authconfigEntities2.get(0);
		rootTree.setTitle(authconfigEntityRoot.getName());
		rootTree.setKey(authconfigEntityRoot.getId() + "");
		rootTree.setExpand(true);
		return rootTree;
	}

	/**
	 * 递归的增加子树
	 */
	private static void getTreeChildren(Dynatree dynatree, List<AuthConfig> authconfigEntities) {
		try {
			List<AuthConfig> authconfigEntitysCerrent = getChildrenAuthConfig(dynatree, authconfigEntities);
			if (!StringUtil.isEmpty(authconfigEntitysCerrent)) {
				List<Dynatree> childrenTrees = new ArrayList<Dynatree>();
				for (AuthConfig authconfigEntity : authconfigEntitysCerrent) {
					Dynatree tree = new Dynatree();
					tree.setKey(authconfigEntity.getId() + "");
					tree.setTitle(authconfigEntity.getName());
					tree.setExpand(true);
					getTreeChildren(tree, authconfigEntities);
					childrenTrees.add(tree);
				}
				dynatree.setChildren(childrenTrees);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static List<AuthConfig> getChildrenAuthConfig(Dynatree dynatree, List<AuthConfig> authconfigEntities)
			throws Exception {
		List<AuthConfig> authconfigEntitys2 = new ArrayList<AuthConfig>();
		for (AuthConfig authconfigEntity : authconfigEntities) {
			if (authconfigEntity.getPid().equals(Long.valueOf(dynatree.getKey()))) {
				authconfigEntitys2.add(authconfigEntity);
			}
		}
		return authconfigEntitys2;
	}
}
